package internal

import (
	"net/http"

	"gitee.com/zhuoyue6/wecom_msg/config"
	"gitee.com/zhuoyue6/wecom_msg/pkg/timesign"
	"github.com/gin-gonic/gin"
)

// ==================== 中间件 ====================

// SignatureMiddleware 签名验证中间件
func SignatureMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		openToken := c.GetHeader("Signature-Token")
		if openToken == config.GlobalConfig.Server.OpenToken {
			c.Next()
			return
		}

		sign := c.GetHeader("X-Sign")
		timestamp := c.GetHeader("X-Time")
		if sign == "" || timestamp == "" {
			c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{
				"code":    400,
				"message": "缺少签名参数",
			})
			return
		}

		signer, _ := timesign.New(config.GlobalConfig.Server.SecretKey)
		if !signer.Verify(sign, timestamp) {
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
				"code":    401,
				"message": "签名验证失败",
			})
			return
		}
		c.Next()
	}
}
